const {Service} = require("ee-core");
const cheerio = require("cheerio");
const {get} = require("axios");
const {createWriteStream, existsSync, mkdirSync} = require("fs");
const axios = require("axios");
const {join} = require("path");
const uuid = require("uuid");
const wallpaper = require('desktop-wallpaper');
const puppeteer = require("puppeteer");
const {json} = require("../utils");

class WallpaperService extends Service {
    url = 'https://haowallpaper.com/'
    typeObj = {
        '电脑壁纸': 'homeView',
        '手机壁纸': 'mobileView'
    }

    constructor(ctx) {
        super(ctx);
    }

    async setWallpaper(args) {
        return new Promise(async (resolve, reject) => {
            try {
                let p = join(__dirname, `../wallpaper`)
                if (!existsSync(p)) mkdirSync(p)
                let imagePath = join(p, `${uuid.v4().replaceAll('-', '')}.png`)
                const params = {
                    url: args.url.replace('getCroppingImg', 'previewFileImg'),
                    savePath: imagePath
                }
                console.log(params.url)
                await this.downloadToDir(params)
                if (existsSync(imagePath)) {
                    if (!args.index) args.index = [0]
                    for (let item of args.index) {
                        await wallpaper.setWallpaper(Number(item), imagePath)
                    }
                    resolve()
                } else {
                    reject(new Error('文件不存在'))
                }
            } catch (e) {
                reject(e)
            }
        })

    }

    async downloadToDir(args) {
        return new Promise(async (resolve, reject) => {
            try {
                // 发送 GET 请求并设置 responseType 为 stream
                const response = await axios({
                    method: 'get',
                    url: args.url,
                    responseType: 'stream'
                });

                // 创建写入流
                const writer = createWriteStream(args.savePath);

                // 将响应数据通过管道写入文件
                response.data.pipe(writer);

                // 等待写入完成
                writer.on('finish', () => {
                    console.log(`文件已下载并保存到: ${args.savePath}`);
                    resolve(args.savePath)
                });

                // 监听错误事件
                writer.on('error', (err) => {
                    reject(err)
                    console.error('下载过程中出错:', err);
                });
            } catch (error) {
                reject(error)
                console.error('下载失败:', error);
            }
        })


    }


    async getPageData(args) {
        return new Promise(async (resolve, reject) => {
            try {
                const {page = 1, type = '/for_desktop', search = '', cate = '', order = '', resolution = ''} = args
                let page_url
                if (!search) {
                    page_url = `https://wallspic.com/cn/album/${order}${type}${resolution ? `${resolution}` : resolution}${cate ? `${cate}` : cate}?page=${page}`
                } else {
                    page_url = `https://wallspic.com/cn${search ? '/search/' + search : ''}?page=${page}`
                }
                page_url = encodeURI(page_url);
                console.log(page_url)
                let res = await axios.get(page_url)
                let data = []
                let $ = cheerio.load(res.data);
                let scripts = $('script[type="application/ld+json"]');
                let select = []
                $('#drop-category select option').each((index, ele) => {
                    let v = $(ele).attr('value')
                    console.log(v.split('/'))
                    select.push({
                        label: $(ele).text().replace(/\s+/g, ''),
                        value: v.split('/')[v.split('/').length - 1]
                    })
                })
                console.log(select)
                scripts.each((index, element) => {
                    const jsonData = JSON.parse($(element).html());
                    if (Array.isArray(jsonData)) {
                        data = jsonData.map(el => {
                            return {
                                title: el.description,
                                download_url: el.contentUrl,
                                src: el.thumbnail ? el.thumbnail.contentUrl.replace('550x310', '500x') : el.contentUrl.replace('550x310', '500x')
                            }
                        })

                    }
                })
                resolve({code: 200, data, select})
            } catch (e) {
                reject(e)
            }
        })
    }
}

module
    .exports = WallpaperService;